package com.ysd.lis.service.sta.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.dto.UploadCipherText;
import com.ysd.lis.dto.sta.StaModuleDto;
import com.ysd.lis.dto.sta.StaModuleParam;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.sta.*;
import com.ysd.lis.mapper.sta.StaModelMenuMapper;
import com.ysd.lis.mapper.sta.StaModuleMapper;
import com.ysd.lis.service.*;
import com.ysd.lis.service.sta.*;
import com.ysd.util.AESUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.sys_module 服务实现类
 * </p>
 *
 * @author prs
 * @since 2024-12-27
 */
@Service
public class StaModuleServiceImpl extends ServiceImpl<StaModuleMapper, StaModule> implements StaModuleService {

    @Autowired
    StaModuleMapper staModuleMapper;


    @Autowired
    StaModelMenuService modelMenuService;

    @Autowired
    StaMenuService staMenuService;

    @Autowired
    SysModuleService sysModuleCopyService;
    @Autowired
    SysMenuService sysMenuCopyService;
    @Autowired
    SysModuleLogService sysModuleLogService;
    @Autowired
    SysMenuLogService sysMenuLogService;
    @Autowired
    StaModelMenuMapper staModelMenuMapper;
    @Autowired
    StaRoleService staRoleService;

    @Autowired
    StaRoleModuleService staRoleModuleService;
    @Autowired
    StaRoleMenuService staRoleMenuService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysRoleModuleService sysRoleModuleService;
    @Autowired
    SysRoleMenuService sysRoleMenuService;

    @Override
    public Result findStaModuleList(StaModuleParam pageParam) {
        MPJLambdaWrapper<StaModule> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.eq(StaModule::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(StaModule::getStaModCode, pageParam.getSeachValue())
                    .or().like(StaModule::getModCode, pageParam.getSeachValue())
                    .or().like(StaModule::getModName, pageParam.getSeachValue()));
        }

        lambdaQueryWrapper.orderByAsc(StaModule::getSeq);
        List<StaModule> supplierPage = staModuleMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", supplierPage);
    }

    @Override
    public Result addStaModule(StaModule staModule) {
        int insert = staModuleMapper.insert(staModule);
        if (insert > 0) {
            return Result.succ(1, "添加成功", staModule);
        } else {
            return Result.fail(400, "添加失败", "");
        }
    }

    @Override
    public Result editStaModule(StaModule supplier) {
        int updateById = staModuleMapper.updateById(supplier);
        if (updateById > 0) {
            return Result.succ(1, "提交成功", supplier);
        } else {
            return Result.fail(400, "修改失败", "");
        }
    }

    @Override
    public Result batchDeleteStaModuleList(StaModuleDto dto) {
        List<StaModule> supplierList = dto.getStaModuleList();
        List<String> ids = supplierList.stream().map(StaModule::getId).collect(Collectors.toList());

        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }


    @Override
    public Result uploadRegisterFile(MultipartFile file, HttpServletRequest request) throws Exception {
        if (file == null) {
            return Result.fail("上传信息不能为空");
        }
        String privateKey = null;
        List<String> modulCodes = new ArrayList<>();
        List<String> codeList = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("-----BEGIN PRIVATE KEY-----")) {
                    privateKey = br.readLine(); // 读取私钥内容
                    br.readLine(); // 跳过 "-----END PRIVATE KEY-----"
                } else {
                    modulCodes.add(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> modulCodeList = modulCodes.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(modulCodeList)) {
            return Result.fail("未找到注册编码");
        }

        List<String> failedList = new ArrayList<>();
        Map<String, String> decryptMap = new HashMap<>();
        for (String modulCode : modulCodeList) {
            String decrypt = AESUtils.decrypt(modulCode);
            if (StringUtils.isNotBlank(decrypt)) {
                codeList.add(decrypt);
                decryptMap.put(decrypt, modulCode);
            } else {
                failedList.add(modulCode);
            }
        }

        List<SysModuleLog> logModules = new ArrayList<>();
        for (String fail : failedList) {
            SysModuleLog moduleLog = new SysModuleLog();
            moduleLog.setState("0");
            moduleLog.setCipherText(fail);
            logModules.add(moduleLog);
        }
        sysModuleLogService.saveBatch(logModules);
        if (CollectionUtil.isEmpty(codeList)) {
            return Result.fail("解密失败");
        }

        MPJLambdaWrapper<StaModule> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.eq(StaModule::getDelFlag, 0);
        lambdaQueryWrapper.in(StaModule::getStaModCode, codeList);
        lambdaQueryWrapper.orderByAsc(StaModule::getSeq);
        List<StaModule> staModules = staModuleMapper.selectList(lambdaQueryWrapper);
        List<String> modCodes = staModules.stream().filter(item -> StringUtils.isNotBlank(item.getModCode())).map(StaModule::getModCode).collect(Collectors.toList());
        // 插入sys_module_copy 后期改成正式的sys_module
        if (CollectionUtil.isNotEmpty(staModules)) {
            for (StaModule newStaModule : staModules) {
                String ciphertext = decryptMap.get(newStaModule.getStaModCode());
                // 创建 SysModuleCopy 和 SysModuleLog 对象 放到集合
                SysModule sysModuleCopy = new SysModule();
                SysModuleLog moduleLog = new SysModuleLog();
                BeanUtil.copyProperties(newStaModule, sysModuleCopy, "id");
                BeanUtil.copyProperties(newStaModule, moduleLog, "id");
                sysModuleCopy.setCode(newStaModule.getModCode());
                sysModuleCopy.setName(newStaModule.getModName());
                sysModuleCopy.setSn(newStaModule.getSeq());
                moduleLog.setStaModCode(newStaModule.getStaModCode());
                moduleLog.setModCode(newStaModule.getModCode());
                moduleLog.setName(newStaModule.getModName());
                moduleLog.setSn(newStaModule.getSeq());
                moduleLog.setCipherText(ciphertext);
                moduleLog.setState("1");
                sysModuleCopyService.saveOrUpdate(sysModuleCopy, new LambdaQueryWrapper<SysModule>().eq(SysModule::getCode, sysModuleCopy.getCode()));
                sysModuleLogService.saveOrUpdate(moduleLog, new LambdaQueryWrapper<SysModuleLog>().eq(SysModuleLog::getModCode, moduleLog.getModCode()));
            }
            Map<String, String> moduleCodeMap = new HashMap<>();
            List<SysModule> sysModuleCopies = sysModuleCopyService.list(new LambdaQueryWrapper<SysModule>().eq(SysModule::getDelFlag, 0).in(SysModule::getCode, modCodes));
            for (SysModule sysModuleCopy : sysModuleCopies) {
                // sysModuleCopy的code匹配staModules集合中的对象modCode，取出sysModuleCopy的对象
                StaModule staModuleOne = staModules.stream().filter(staModule -> staModule.getModCode().equals(sysModuleCopy.getCode())).findFirst().orElse(null);
                moduleCodeMap.put(staModuleOne.getStaModCode(), sysModuleCopy.getId());
            }
            // 获取 staModules 中所有的 modCode
            Set<String> existingModCodes = staModules.stream()
                    .map(StaModule::getStaModCode)
                    .collect(Collectors.toSet());

            // 找出 codeList 中不在 staModules 中的 modCode
            List<String> missingModCodes = codeList.stream()
                    .filter(modCode -> !existingModCodes.contains(modCode))
                    .collect(Collectors.toList());
            for (String missingModCode : missingModCodes) {
                SysModuleLog moduleLog = new SysModuleLog();
                moduleLog.setStaModCode(missingModCode);
                moduleLog.setState("0");
                moduleLog.setCipherText(decryptMap.get(missingModCode));
                logModules.add(moduleLog);
            }

            sysModuleLogService.saveBatch(logModules);

            // 1.根据staModules 查出来STA_MODEL_MENU 的数据,来对比sys_menu_log数据,如果没有就塞入,sys_menu_copy表也要进行塞入

            LambdaQueryWrapper<StaModelMenu> staModuleMenuWrapper = new LambdaQueryWrapper<>();
            staModuleMenuWrapper.eq(StaModelMenu::getDelFlag, 0);
            staModuleMenuWrapper.eq(StaModelMenu::getModelCode, "001");
            staModuleMenuWrapper.in(StaModelMenu::getStaModCode, codeList);
            List<StaModelMenu> staModuleMenus = staModelMenuMapper.selectList(staModuleMenuWrapper);
            List<StaModelMenu> returnList = new ArrayList<>();
            staModuleMenus.forEach(a -> {
                if (StringUtils.isBlank(a.getParentId())) {
                    a.setChildren(this.getChildren(a, staModuleMenus));
                    returnList.add(a);
                }
            });

            if (CollectionUtil.isEmpty(returnList)) {
                return Result.succ(1, "查询成功", "");
            }
            for (StaModelMenu staModuleMenu : returnList) {
                String sysModulId = moduleCodeMap.get(staModuleMenu.getStaModCode());
                SysMenuLog menuLog = new SysMenuLog();

                SysMenu menuCopy = new SysMenu();
                menuCopy.setTitle(staModuleMenu.getMenuTitle());
                menuCopy.setCode(staModuleMenu.getMenuCode());
                menuCopy.setModuleId(sysModulId);
                LambdaQueryWrapper<SysMenu> sysMenuCopyWrapper = new LambdaQueryWrapper<>();
                sysMenuCopyWrapper.eq(SysMenu::getDelFlag, 0);
                sysMenuCopyWrapper.eq(SysMenu::getCode, menuCopy.getCode());
                sysMenuCopyService.saveOrUpdate(menuCopy, sysMenuCopyWrapper);

                BeanUtil.copyProperties(staModuleMenu, menuLog, "id", "parentId");
                menuLog.setStaModCode(staModuleMenu.getStaModCode());
                LambdaQueryWrapper<SysMenuLog> sysMenuLogWrapper = new LambdaQueryWrapper<>();
                sysMenuLogWrapper.eq(SysMenuLog::getDelFlag, 0);
                sysMenuLogWrapper.eq(SysMenuLog::getMenuCode, menuLog.getMenuCode());
                sysMenuLogService.saveOrUpdate(menuLog, sysMenuLogWrapper);

                menuCopy = sysMenuCopyService.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getDelFlag, 0).eq(SysMenu::getCode, menuCopy.getCode())).get(0);
                menuLog = sysMenuLogService.list(new LambdaQueryWrapper<SysMenuLog>().eq(SysMenuLog::getDelFlag, 0).eq(SysMenuLog::getMenuCode, menuLog.getMenuCode())).get(0);
                if (CollectionUtil.isNotEmpty(staModuleMenu.getChildren())) {
                    for (StaModelMenu staModelMenu : staModuleMenu.getChildren()) {
                        SysMenuLog menuLog1 = new SysMenuLog();
                        BeanUtil.copyProperties(staModelMenu, menuLog1, "id", "parentId");
                        menuLog1.setParentId(menuLog.getId());
                        LambdaQueryWrapper<SysMenuLog> sysMenuLog1Wrapper = new LambdaQueryWrapper<>();
                        sysMenuLog1Wrapper.eq(SysMenuLog::getDelFlag, 0);
                        sysMenuLog1Wrapper.eq(SysMenuLog::getMenuCode, menuLog1.getMenuCode());
                        sysMenuLogService.saveOrUpdate(menuLog1, sysMenuLog1Wrapper);

                        // 查询sta_menue 塞入sys_menu_copy
                        List<StaMenu> staMenus = staMenuService.list(new LambdaQueryWrapper<StaMenu>().eq(StaMenu::getDelFlag, 0).in(StaMenu::getMenuCode, staModelMenu.getMenuCode()));
                        StaMenu staMenu = staMenus.get(0);
                        SysMenu menuCopy1 = new SysMenu();
                        BeanUtil.copyProperties(staMenu, menuCopy1, "id", "parentId");
                        menuCopy1.setTitle(staMenu.getMenuTitle());
                        menuCopy1.setSn(staMenu.getSeq());
                        menuCopy1.setModuleId(sysModulId);
                        menuCopy1.setParentId(menuCopy.getId());
                        menuCopy1.setCode(staModelMenu.getMenuCode());
                        LambdaQueryWrapper<SysMenu> sysMenuCopyWrapper1 = new LambdaQueryWrapper<>();
                        sysMenuCopyWrapper1.eq(SysMenu::getDelFlag, 0);
                        sysMenuCopyWrapper1.eq(SysMenu::getCode, menuCopy1.getCode());
                        sysMenuCopyService.saveOrUpdate(menuCopy1, sysMenuCopyWrapper1);
                    }
                }
            }
            //根据模块去查询标准角色 动态生成角色菜单
            saveOrUpdateRole(codeList,moduleCodeMap);
        }
        return Result.succ(1, "注册成功", "");
    }

    @Override
    public Result uploadRegisterCipherText(UploadCipherText uploadCipherText) throws Exception {
        String cipherText = uploadCipherText.getCipherText();
        cipherText = cipherText.replaceAll("\\s+", "");
        List<String> codeList = new ArrayList<>();
        List<String> failedList = new ArrayList<>();
        Map<String, String> decryptMap = new HashMap<>();
        String decrypt = AESUtils.decrypt(cipherText);
        if (StringUtils.isNotBlank(decrypt)) {
            codeList.add(decrypt);
            decryptMap.put(decrypt, cipherText);
        } else {
            failedList.add(cipherText);
        }

        List<SysModuleLog> logModules = new ArrayList<>();
        for (String fail : failedList) {
            SysModuleLog moduleLog = new SysModuleLog();
            moduleLog.setState("0");
            moduleLog.setCipherText(fail);
            logModules.add(moduleLog);
        }
        sysModuleLogService.saveBatch(logModules);
        if (CollectionUtil.isEmpty(codeList)) {
            return Result.fail("解密失败");
        }
        MPJLambdaWrapper<StaModule> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.eq(StaModule::getDelFlag, 0);
        lambdaQueryWrapper.in(StaModule::getStaModCode, codeList);
        lambdaQueryWrapper.orderByAsc(StaModule::getSeq);
        List<StaModule> staModules = staModuleMapper.selectList(lambdaQueryWrapper);
        List<String> modCodes = staModules.stream().filter(item -> StringUtils.isNotBlank(item.getModCode())).map(StaModule::getModCode).collect(Collectors.toList());
        // 插入sys_module_copy 后期改成正式的sys_module
        if (CollectionUtil.isNotEmpty(staModules)) {
            for (StaModule newStaModule : staModules) {
                String ciphertext = decryptMap.get(newStaModule.getStaModCode());
                // 创建 SysModuleCopy 和 SysModuleLog 对象 放到集合
                SysModule sysModuleCopy = new SysModule();
                SysModuleLog moduleLog = new SysModuleLog();
                BeanUtil.copyProperties(newStaModule, sysModuleCopy, "id");
                BeanUtil.copyProperties(newStaModule, moduleLog, "id");
                sysModuleCopy.setCode(newStaModule.getModCode());
                sysModuleCopy.setName(newStaModule.getModName());
                sysModuleCopy.setSn(newStaModule.getSeq());
                moduleLog.setStaModCode(newStaModule.getStaModCode());
                moduleLog.setModCode(newStaModule.getModCode());
                moduleLog.setName(newStaModule.getModName());
                moduleLog.setSn(newStaModule.getSeq());
                moduleLog.setCipherText(ciphertext);
                moduleLog.setState("1");
                sysModuleCopyService.saveOrUpdate(sysModuleCopy, new LambdaQueryWrapper<SysModule>().eq(SysModule::getCode, sysModuleCopy.getCode()));
                sysModuleLogService.saveOrUpdate(moduleLog, new LambdaQueryWrapper<SysModuleLog>().eq(SysModuleLog::getModCode, moduleLog.getModCode()));
            }
            Map<String, String> moduleCodeMap = new HashMap<>();
            List<SysModule> sysModuleCopies = sysModuleCopyService.list(new LambdaQueryWrapper<SysModule>().eq(SysModule::getDelFlag, 0).in(SysModule::getCode, modCodes));
            for (SysModule sysModuleCopy : sysModuleCopies) {
                // sysModuleCopy的code匹配staModules集合中的对象modCode，取出sysModuleCopy的对象
                StaModule staModuleOne = staModules.stream().filter(staModule -> staModule.getModCode().equals(sysModuleCopy.getCode())).findFirst().orElse(null);
                moduleCodeMap.put(staModuleOne.getStaModCode(), sysModuleCopy.getId());
            }
            // 获取 staModules 中所有的 modCode
            Set<String> existingModCodes = staModules.stream()
                    .map(StaModule::getStaModCode)
                    .collect(Collectors.toSet());

            // 找出 codeList 中不在 staModules 中的 modCode
            List<String> missingModCodes = codeList.stream()
                    .filter(modCode -> !existingModCodes.contains(modCode))
                    .collect(Collectors.toList());
            for (String missingModCode : missingModCodes) {
                SysModuleLog moduleLog = new SysModuleLog();
                moduleLog.setStaModCode(missingModCode);
                moduleLog.setState("0");
                moduleLog.setCipherText(decryptMap.get(missingModCode));
                logModules.add(moduleLog);
            }

            sysModuleLogService.saveBatch(logModules);

            // 1.根据staModules 查出来STA_MODEL_MENU 的数据,来对比sys_menu_log数据,如果没有就塞入,sys_menu_copy表也要进行塞入

            LambdaQueryWrapper<StaModelMenu> staModuleMenuWrapper = new LambdaQueryWrapper<>();
            staModuleMenuWrapper.eq(StaModelMenu::getDelFlag, 0);
            staModuleMenuWrapper.eq(StaModelMenu::getModelCode, "001");
            staModuleMenuWrapper.in(StaModelMenu::getStaModCode, codeList);
            List<StaModelMenu> staModuleMenus = staModelMenuMapper.selectList(staModuleMenuWrapper);
            List<StaModelMenu> returnList = new ArrayList<>();
            staModuleMenus.forEach(a -> {
                if (StringUtils.isBlank(a.getParentId())) {
                    a.setChildren(this.getChildren(a, staModuleMenus));
                    returnList.add(a);
                }
            });

            if (CollectionUtil.isEmpty(returnList)) {
                return Result.succ(1, "查询成功", "");
            }
            for (StaModelMenu staModuleMenu : returnList) {
                String sysModulId = moduleCodeMap.get(staModuleMenu.getStaModCode());
                SysMenuLog menuLog = new SysMenuLog();

                SysMenu menuCopy = new SysMenu();
                menuCopy.setTitle(staModuleMenu.getMenuTitle());
                menuCopy.setCode(staModuleMenu.getMenuCode());
                menuCopy.setModuleId(sysModulId);
                LambdaQueryWrapper<SysMenu> sysMenuCopyWrapper = new LambdaQueryWrapper<>();
                sysMenuCopyWrapper.eq(SysMenu::getDelFlag, 0);
                sysMenuCopyWrapper.eq(SysMenu::getCode, menuCopy.getCode());
                sysMenuCopyService.saveOrUpdate(menuCopy, sysMenuCopyWrapper);

                BeanUtil.copyProperties(staModuleMenu, menuLog, "id", "parentId");
                menuLog.setStaModCode(staModuleMenu.getStaModCode());
                LambdaQueryWrapper<SysMenuLog> sysMenuLogWrapper = new LambdaQueryWrapper<>();
                sysMenuLogWrapper.eq(SysMenuLog::getDelFlag, 0);
                sysMenuLogWrapper.eq(SysMenuLog::getMenuCode, menuLog.getMenuCode());
                sysMenuLogService.saveOrUpdate(menuLog, sysMenuLogWrapper);

                menuCopy = sysMenuCopyService.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getDelFlag, 0).eq(SysMenu::getCode, menuCopy.getCode())).get(0);
                menuLog = sysMenuLogService.list(new LambdaQueryWrapper<SysMenuLog>().eq(SysMenuLog::getDelFlag, 0).eq(SysMenuLog::getMenuCode, menuLog.getMenuCode())).get(0);
                if (CollectionUtil.isNotEmpty(staModuleMenu.getChildren())) {
                    for (StaModelMenu staModelMenu : staModuleMenu.getChildren()) {
                        SysMenuLog menuLog1 = new SysMenuLog();
                        BeanUtil.copyProperties(staModelMenu, menuLog1, "id", "parentId");
                        menuLog1.setParentId(menuLog.getId());
                        LambdaQueryWrapper<SysMenuLog> sysMenuLog1Wrapper = new LambdaQueryWrapper<>();
                        sysMenuLog1Wrapper.eq(SysMenuLog::getDelFlag, 0);
                        sysMenuLog1Wrapper.eq(SysMenuLog::getMenuCode, menuLog1.getMenuCode());
                        sysMenuLogService.saveOrUpdate(menuLog1, sysMenuLog1Wrapper);

                        // 查询sta_menue 塞入sys_menu_copy
                        List<StaMenu> staMenus = staMenuService.list(new LambdaQueryWrapper<StaMenu>().eq(StaMenu::getDelFlag, 0).in(StaMenu::getMenuCode, staModelMenu.getMenuCode()));
                        StaMenu staMenu = staMenus.get(0);
                        SysMenu menuCopy1 = new SysMenu();
                        BeanUtil.copyProperties(staMenu, menuCopy1, "id", "parentId");
                        menuCopy1.setTitle(staMenu.getMenuTitle());
                        menuCopy1.setSn(staMenu.getSeq());
                        menuCopy1.setModuleId(sysModulId);
                        menuCopy1.setParentId(menuCopy.getId());
                        menuCopy1.setCode(staModelMenu.getMenuCode());
                        LambdaQueryWrapper<SysMenu> sysMenuCopyWrapper1 = new LambdaQueryWrapper<>();
                        sysMenuCopyWrapper1.eq(SysMenu::getDelFlag, 0);
                        sysMenuCopyWrapper1.eq(SysMenu::getCode, menuCopy1.getCode());
                        sysMenuCopyService.saveOrUpdate(menuCopy1, sysMenuCopyWrapper1);
                    }
                }
            }
            //根据模块去查询标准角色 动态生成角色菜单
            saveOrUpdateRole(codeList,moduleCodeMap);
        }

        return Result.succ(1, "注册成功", "");
    }


    //维护标准角色 模块和菜单
    public void saveOrUpdateRole(List<String> codeList,Map<String, String> moduleCodeMap) {
        List<StaRole> roleList = staRoleService.list(new LambdaQueryWrapper<StaRole>().eq(StaRole::getDelFlag, 0).eq(StaRole::getModelCode, "001"));
        if (CollectionUtil.isNotEmpty(roleList)){
            for (StaRole staRole : roleList) {
                SysRole sysRole=new SysRole();
                sysRole.setCode(staRole.getRoleCode());
                sysRole.setRoleName(staRole.getRoleName());
                sysRole.setIsOpen("1");
                sysRoleService.saveOrUpdate(sysRole, new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, sysRole.getCode()).eq(SysRole::getDelFlag, 0));
                sysRole = sysRoleService.list(new LambdaQueryWrapper<SysRole>().eq(SysRole::getDelFlag, 0).eq(SysRole::getCode, sysRole.getCode())).get(0);

                List<StaRoleModule> staRoleModules = staRoleModuleService.list(new LambdaQueryWrapper<StaRoleModule>().eq(StaRoleModule::getModelCode, "001").eq(StaRoleModule::getStaRoleCode, staRole.getStaRoleCode()).eq(StaRoleModule::getDelFlag, 0).in(StaRoleModule::getStaModCode, codeList));

                if (CollectionUtil.isNotEmpty(staRoleModules)){
                    for (StaRoleModule staRoleModule : staRoleModules) {
                        SysRoleModule sysRoleModule=new SysRoleModule();
                        sysRoleModule.setRoleId(sysRole.getId());
                        sysRoleModule.setModuleId(moduleCodeMap.get(staRoleModule.getStaModCode()));
                        sysRoleModuleService.saveOrUpdate(sysRoleModule, new LambdaQueryWrapper<SysRoleModule>().eq(SysRoleModule::getRoleId, sysRoleModule.getRoleId()).eq(SysRoleModule::getModuleId, sysRoleModule.getModuleId()));
                        sysRoleModule = sysRoleModuleService.list(new LambdaQueryWrapper<SysRoleModule>().eq(SysRoleModule::getDelFlag, 0).eq(SysRoleModule::getRoleId, sysRoleModule.getRoleId()).eq(SysRoleModule::getModuleId, sysRoleModule.getModuleId())).get(0);

                        List<StaRoleMenu> staRoleMenus = staRoleMenuService.list(new LambdaQueryWrapper<StaRoleMenu>().eq(StaRoleMenu::getModelCode, "001").eq(StaRoleMenu::getStaRoleCode, staRole.getStaRoleCode()).eq(StaRoleMenu::getDelFlag, 0).eq(StaRoleMenu::getStaModCode, staRoleModule.getStaModCode()));
                        List<String> menuCodeList = staRoleMenus.stream().filter(item -> StringUtils.isNotBlank(item.getMenuCode())).map(StaRoleMenu::getMenuCode).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(menuCodeList)){
                            List<SysMenu> sysMenuList = sysMenuCopyService.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getDelFlag, 0).in(SysMenu::getCode, menuCodeList));
                            Map<String, String> sysMenuMap = sysMenuList.stream().collect(Collectors.toMap(SysMenu::getCode, SysMenu::getId));
                            if (CollectionUtil.isNotEmpty(staRoleMenus)){
                         /*   List<StaRoleMenu> returnList = new ArrayList<>();
                            staRoleMenus.forEach(a -> {
                                if (StringUtils.isBlank(a.getParentId())) {
                                    a.setChildren(this.getStaRoleChildren(a, staRoleMenus));
                                    returnList.add(a);
                                }
                            });*/
                                for (StaRoleMenu staRoleMenu : staRoleMenus ) {
                                    SysRoleMenu sysRoleMenu=new SysRoleMenu();
                                    sysRoleMenu.setRoleModuleId(sysRoleModule.getId());
                                    sysRoleMenu.setRoleId(sysRole.getId());
                                    sysRoleMenu.setMenuId(sysMenuMap.get(staRoleMenu.getMenuCode()));
                                    sysRoleMenu.setModuleId(moduleCodeMap.get(staRoleModule.getStaModCode()));
                                    sysRoleMenuService.saveOrUpdate(sysRoleMenu, new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, sysRoleMenu.getRoleId()).eq(SysRoleMenu::getMenuId, sysRoleMenu.getMenuId()).eq(SysRoleMenu::getRoleModuleId, sysRoleMenu.getRoleModuleId()));

                                }
                            }
                        }

                    }
                }

            }
        }
    }

    public List<StaModelMenu> getChildren(StaModelMenu a, List<StaModelMenu> menuList) {
        List<StaModelMenu> result = new ArrayList();
        for (StaModelMenu menu : menuList) {
            if (StringUtils.isBlank(menu.getParentId())) {
                menu.setParentName("");
            }

            if (StringUtils.isNotBlank(menu.getParentId()) && menu.getParentId().equals(a.getId())) {
                menu.setParentName(a.getMenuTitle());
                result.add(menu);
            }

        }
        for (StaModelMenu menu : result) {
            menu.setChildren(getChildren(menu, menuList));
        }
        if (result.size() == 0) {
            return new ArrayList<>();
        }
        return result;

    }

    public List<StaRoleMenu> getStaRoleChildren(StaRoleMenu a, List<StaRoleMenu> menuList) {
        List<StaRoleMenu> result = new ArrayList();
        for (StaRoleMenu menu : menuList) {
            if (StringUtils.isBlank(menu.getParentId())) {
                menu.setParentName("");
            }

            if (StringUtils.isNotBlank(menu.getParentId()) && menu.getParentId().equals(a.getId())) {
                menu.setParentName(a.getMenuTitle());
                result.add(menu);
            }

        }
        for (StaRoleMenu menu : result) {
            menu.setChildren(getStaRoleChildren(menu, menuList));
        }
        if (result.size() == 0) {
            return new ArrayList<>();
        }
        return result;

    }
}
